package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.ContractProductDao;
import com.xbongbong.saas.domain.entity.BusinessProductEntity;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.enums.ContractProductTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.subform.ContractProductSubFormEnum;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author long.rao
 * @version v1.0
 * @date 2019/2/23 15:34
 * @since v1.0
 */
@Service("contractProductModel")
public class ContractProductModelImpl implements ContractProductModel {
    @Resource
    private ContractProductDao contractProductDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;

    @Override
    public Integer insert(ContractProductEntity entity) throws XbbException {
        // 关联产品过滤不需要存储的逻辑字段
        List<String> removeKeys = Arrays.asList("estimateCost", "productSubId", "enableMultiUnit", "refProductId", "shelfLifeDays", "enableBatchShelfLife", "enableSerialNumber");
        removeKeys.forEach(entity.getData()::remove);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer result = contractProductDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferContractProductToFormData(entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
        paasEsModel.insert(saveDTO);
//        paasEsModel.insert(entity,IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT,entity.getCorpid(),entity.getId(),entity.getContractId());
        return result;
    }


    @Override
    public Integer insertBatch(List<ContractProductEntity> insertList) throws XbbException {
        if (CollectionUtils.isEmpty(insertList)) {
            return 0;
        }
        List<String> removeKeys = Arrays.asList("estimateCost", "productSubId", "enableMultiUnit", "refProductId", "shelfLifeDays", "enableBatchShelfLife", "enableSerialNumber");
        long now = DateTimeUtil.getInt();
        insertList.forEach(item->{
            removeKeys.forEach(item.getData()::remove);
            item.setAddTime(now);
            item.setUpdateTime(now);
            item.setDel(DelEnum.NORMAL.getDel());
        });
        StandardizeDataUtil.standardize4ContractEntityList(insertList);
        Integer integer = contractProductDao.insertBatch(insertList);
        List<? extends PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferContractProductToFormDataList(insertList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity item : paasFormDataEntities) {
            InsertDTO saveDTO = paasEsModel.getSaveDTO(item, IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
            insertDTOList.add(saveDTO);
        }
        paasEsModel.insertBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE);
        return integer;
    }

    @Override
    public Integer update(ContractProductEntity entity) throws XbbException {
        // 关联产品过滤不需要存储的逻辑字段
        List<String> removeKeys = Arrays.asList("estimateCost", "productSubId", "enableMultiUnit", "refProductId", "shelfLifeDays", "enableBatchShelfLife", "enableSerialNumber");
        removeKeys.forEach(entity.getData()::remove);
        entity.setUpdateTime(DateUtil.getNow());
        StandardizeDataUtil.standardizeNotString(entity);
        Integer resutlt = contractProductDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferContractProductToFormData(entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
        paasEsModel.update(saveDTO);
//        paasEsModel.update(entity,IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT,entity.getCorpid(),entity.getId(),entity.getContractId());
        return resutlt;
    }

    @Override
    public List<ContractProductEntity> findEntitys(Map<String, Object> param) {
        return contractProductDao.findEntitys(param);
    }

    @Override
    public List<ContractProductEntity> getSortProducts(Map<String, Object> param) {
        return contractProductDao.getSortProducts(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return contractProductDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public ContractProductEntity getByKey(Long key, String corpid) {
        return contractProductDao.getByKey(key, corpid);
    }

    @Override
    public List<ContractProductEntity> getProductsByConId(Long conId, String corpid, List<Integer> del) {
        // 获取合同关联产品
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid", corpid);
        params.put("delIn", del);
        params.put("contractId", conId);
        params.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        return findEntitys(params);
    }
    @Override
    public List<ContractProductEntity> getProductsByConId(Long conId, String corpid) {
        if (Objects.isNull(conId)) {
            throw new IllegalArgumentException("getProductsByConId : conId 参数不能为空!");
        }
        // 获取合同关联产品
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid", corpid);
        params.put("del", DelEnum.NORMAL.getDel());
        params.put("contractId", conId);
        params.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        return findEntitys(params);
    }

    @Override
    public List<ContractProductEntity> getAllContractProduct(String corpid, Integer isProduce) {
        String stockAttr = "$." + ProductEnum.STOCK.getAttr();
        Integer type = ContractProductTypeEnum.CONTNRACT.getCode();
        return contractProductDao.getAllContractProduct(corpid,isProduce,stockAttr,type);
    }

    @Override
    public List<ContractProductEntity> getContractProductByContractIdIn(String corpid, Integer isProduce, List<Long> contractIdIn) {
        return contractProductDao.getContractProductByContractIdIn(corpid, isProduce, contractIdIn);
    }

    @Override
    public List<ContractProductEntity> getContractProductByContractIdIn(String corpid, List<Long> contractIdIn) {
        if (Objects.isNull(contractIdIn)) {
            throw new IllegalArgumentException("getContractProductByContractIdIn : contractIdIn 参数不能为空!");
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("contractIdIn", contractIdIn);
        param.put("del", 0);
        param.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        return findEntitys(param);
    }

    @Override
    public List<ContractProductEntity> getContractProductByProductIdIn(String corpid, Integer isProduce, List<Long> productIdIn) {
        return contractProductDao.getContractProductByProductIdIn(corpid, isProduce, productIdIn);
    }
    /**
     * 报表中心产品销售汇总表（获取实体并求出产品总数量、产品总销售金额、产品总成本）
     *
     * @param param productIdIn,page,corpid,del,contractIdIn,pageNum,start,orderByStr(sum_product_num desc, sum_price desc)
     * @return java.util.List<com.xbongbong.saas.domain.entity.ContractProductEntity>
     * @author 徐俊杰
     * @date 2019/3/5 17:29
     * @since v1.0
     */
    @Override
    public List<ContractProductEntity> findEntitysForTarget(Map<String, Object> param) {
        return contractProductDao.findEntitysForTarget(param);
    }

    /**
     * 报表中心产品销售汇总表（总量）
     *
     * @param param productIdIn,page,corpid,del,contractIdIn,pageNum,start,orderByStr(sum_product_num desc, sum_price desc)
     * @return java.lang.Integer
     * @author 徐俊杰
     * @date 2019/3/5 19:30
     * @since v1.0
     */
    @Override
    public Integer getEntitysCountForTarget(Map<String, Object> param) {
        return contractProductDao.getEntitysCountForTarget(param);
    }

    @Override
    public Integer deleteContractAllProduct(List<Long> contractIdIn, String corpid, Integer del) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("contractIdIn", contractIdIn);
        List<ContractProductEntity> contractProductList = contractProductDao.findEntitys(param);
        Integer delete = contractProductDao.deleteContractAllProduct(contractIdIn, corpid, del);
        if (CollectionUtils.isNotEmpty(contractProductList)) {
            List<InsertDTO> insertList = new ArrayList<>();
            for (ContractProductEntity entity : contractProductList){
                InsertDTO insertDTO = new InsertDTO();
                insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getType() + "_" + corpid + "_" + entity.getId());
                insertDTO.setParent(corpid + "_" + entity.getContractId());
                Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put(ParameterConstant.DEL, del);
                map.put("updateTime", DateTimeUtil.getInt());
                insertDTO.setSource(map);
                insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
                insertList.add(insertDTO);
            }
            paasEsModel.updateBatch(insertList);
        }
        return delete;
    }

    @Override
    public Integer updateBatch(List<ContractProductEntity> updateList, String corpid) throws XbbException {
        // 关联产品过滤不需要存储的逻辑字段
        List<String> removeKeys = Arrays.asList("estimateCost", "productSubId", "enableMultiUnit", "refProductId", "shelfLifeDays", "enableBatchShelfLife", "enableSerialNumber");
        for (ContractProductEntity entity : updateList) {
            removeKeys.forEach(entity.getData()::remove);
            entity.setUpdateTime(DateUtil.getNow());
        }
        StandardizeDataUtil.standardize4ContractEntityList(updateList);
        Integer result = contractProductDao.updateBatch(updateList,corpid);
        List<? extends PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferContractProductToFormDataList(updateList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT));
        }

//        for (ContractProductEntity entity : updateList){
//            InsertDTO insertDTO = new InsertDTO();
//            insertDTO.setEsId(corpid + "_" + entity.getId());
//            insertDTO.setParent(corpid + "_" + entity.getContractId());
//            insertDTO.setSource(BeanUtil.convertBean2Map(entity,false,true));
//            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
//            insertDTOList.add(insertDTO);
//        }
        paasEsModel.updateBatch(insertDTOList);
        return result;
    }


    @Override
    public Integer updateMulti(List<ContractProductEntity> updateList, String corpid) throws XbbException {
        if (CollectionUtils.isEmpty(updateList)) {
            return 0;
        }
        // 关联产品过滤不需要存储的逻辑字段
        List<String> removeKeys = Arrays.asList("estimateCost", "productSubId", "enableMultiUnit", "refProductId", "shelfLifeDays", "enableBatchShelfLife", "enableSerialNumber");
        long now = DateUtil.getNow();
        for (ContractProductEntity entity : updateList) {
            removeKeys.forEach(entity.getData()::remove);
            entity.setUpdateTime(now);
        }
        StandardizeDataUtil.standardize4ContractEntityList(updateList);
        Integer result = contractProductDao.updateMulti(updateList,corpid);
        List<? extends PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferContractProductToFormDataList(updateList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT));
        }

        paasEsModel.updateBatch(insertDTOList);
        return result;
    }

    @Override
    public Integer updateBatchImmediately(List<ContractProductEntity> updateList, String corpid) throws XbbException {
        if (CollectionUtils.isEmpty(updateList)) {
            return 0;
        }
        // 关联产品过滤不需要存储的逻辑字段
        List<String> removeKeys = Arrays.asList("estimateCost", "productSubId", "enableMultiUnit", "refProductId", "shelfLifeDays", "enableBatchShelfLife", "enableSerialNumber");
        long now = DateUtil.getNow();
        for (ContractProductEntity entity : updateList) {
            removeKeys.forEach(entity.getData()::remove);
            entity.setUpdateTime(now);
        }
        StandardizeDataUtil.standardize4ContractEntityList(updateList);
        Integer result = contractProductDao.updateBatch(updateList,corpid);
        List<? extends PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferContractProductToFormDataList(updateList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT));
        }
//
//        for (ContractProductEntity entity : updateList){
//            InsertDTO insertDTO = new InsertDTO();
//            insertDTO.setEsId(corpid + "_" + entity.getId());
//            insertDTO.setParent(corpid + "_" + entity.getContractId());
//            insertDTO.setSource(BeanUtil.convertBean2Map(entity,false,true));
//            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
//            insertDTOList.add(insertDTO);
//        }
        paasEsModel.updateBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE);
        return result;
    }

    @Override
    public Integer updateOutStock(List<ContractProductEntity> updateList, String corpid) throws XbbException {
        // 关联产品过滤不需要存储的逻辑字段
        List<String> removeKeys = Arrays.asList("estimateCost", "productSubId", "enableMultiUnit", "refProductId", "shelfLifeDays", "enableBatchShelfLife", "enableSerialNumber");
        long now = DateUtil.getNow();
        for (ContractProductEntity entity : updateList) {
            removeKeys.forEach(entity.getData()::remove);
            entity.setUpdateTime(now);
        }
        StandardizeDataUtil.standardize4ContractEntityList(updateList);
        Integer result = contractProductDao.updateOutStock(updateList,corpid);
        List<? extends PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferContractProductToFormDataList(updateList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT));
        }
        // for (ContractProductEntity entity : updateList){
        //     InsertDTO insertDTO = new InsertDTO();
        //     insertDTO.setEsId(corpid + "_" + entity.getId());
        //     insertDTO.setParent(corpid + "_" + entity.getContractId());
        //     insertDTO.setSource(BeanUtil.convertBean2Map(entity,false,true));
        //     insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
        //     insertDTOList.add(insertDTO);
        // }
        paasEsModel.updateBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE);
        return result;
    }

    @Override
    public List<BusinessProductEntity> findProductNum(Map<String, Object> param) {
        return contractProductDao.findProductNum(param);
    }

    @Override
    public Integer findProductNumCount(Map<String, Object> param) {
        return contractProductDao.findProductNumCount(param);
    }

    @Override
    public List<BusinessProductEntity> findProductNumIncludeProcess(Map<String, Object> param) {
        return contractProductDao.findProductNumIncludeProcess(param);
    }

    @Override
    public Integer findProductNumCountIncludeProcess(Map<String, Object> param) {
        return contractProductDao.findProductNumCountIncludeProcess(param);
    }

    @Override
    public void reductionEsInUpdate(List<ContractProductEntity> contractProductList) throws XbbException {
        List<? extends PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferContractProductToFormDataList(contractProductList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT));
        }

//        for (ContractProductEntity entity : contractProductList){
//            InsertDTO insertDTO = new InsertDTO();
//            insertDTO.setEsId(entity.getCorpid() + "_" + entity.getId());
//            insertDTO.setParent(entity.getCorpid() + "_" + entity.getContractId());
//            insertDTO.setSource(BeanUtil.convertBean2Map(entity,false,true));
//            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
//            insertDTOList.add(insertDTO);
//        }
        paasEsModel.updateBatch(insertDTOList);
    }

    @Override
    public List<ContractProductEntity> getContractCost(Long contractId, String corpid) {
        return contractProductDao.getContractCost(contractId,corpid);
    }

    @Override
    public Long isProductSubAttrExist(String attr, String corpid, Integer type, Long formId, Integer isArray) {
        return contractProductDao.isProductSubAttrExist(attr,corpid,type,formId,isArray);
    }

    @Override
    public Long countProductSub(String attr, String corpid, Integer type, Long formId, Integer isArray) {
        return contractProductDao.countProductSub(attr, corpid, type, formId, isArray);
    }

    @Override
    public void updateInStock(List<ContractProductEntity> updateList, String corpid) {
        long now = DateTimeUtil.getInt();
        updateList.forEach(item->{
            item.setUpdateTime(now);
        });
        contractProductDao.updateInStock(updateList,corpid);
    }

    @Override
    public void updateInStockForJob(List<ContractProductEntity> updateList, String corpid) {
        long now = DateTimeUtil.getInt();
        updateList.forEach(item->{
            item.setUpdateTime(now);
        });
        contractProductDao.updateInStockForJob(updateList,corpid);
    }

    @Override
    public void updateOutStockForJob(List<ContractProductEntity> updateList, String corpid) {
        long now = DateTimeUtil.getInt();
        updateList.forEach(item->{
            item.setUpdateTime(now);
        });
        contractProductDao.updateOutStockForJob(updateList,corpid);
    }

    @Override
    public Double summaryByAttr(String field,String corpid,  Long refId, List<Long> productIdIn,Integer type){
        return contractProductDao.summaryByAttr( field,corpid, refId, productIdIn,type);
    }

    @Override
    public Double summaryByAttrFromOutSide(String field,String corpid,  Long refId, List<Long> productIdIn,Integer type){
        return contractProductDao.summaryByAttrFromOutSide( field,corpid, refId, productIdIn,type);
    }

    /**
     * 根据主键删除记录
     *
     * @param key    主键
     * @param corpid 公司id
     * @return java.lang.Integer
     * @author youli.chen
     * @date 2019/2/21 15:18
     */
    @Override
    public Integer deleteByKey(Long key, String corpid) {
        return contractProductDao.deleteByKey(key,corpid);
    }

    @Override
    public Double calcuateByAttrFromOutSide(String field1, String field2, String corpid, Long refId, List<Long> productIdIn, Integer type) {
        return contractProductDao.calcuateByAttrFromOutSide(field1, field2, corpid, refId ,productIdIn ,type);
    }

    @Override
    public Integer updateIsProduceByProductId(Integer isProduce, String corpid, List<Long> productIdList) throws XbbException {
        // 更新ES数据
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put("productIdIn", productIdList);
        param.put("del", 0);
        List<ContractProductEntity> contractProductList = contractProductDao.findEntitys(param);
        if(CollectionUtils.isNotEmpty(contractProductList)){
            List<ContractProductEntity> newContractProductList = contractProductList.stream().peek(entity -> entity.setIsProduce(isProduce)).collect(Collectors.toList());
            this.reductionEsInUpdate(newContractProductList);
        }
        // 更新数据库数据
        return contractProductDao.updateIsProduceByProductId(isProduce, corpid, productIdList);
    }

    @Override
    public List<ContractProductEntity> getProductWithSubData(String attr, String corpid, Integer type, Long formId, Integer isArray, Long idGte, Integer limit) {
        return contractProductDao.getProductWithSubData(attr, corpid, type, formId, isArray, idGte, limit);
    }

    @Override
    public Integer deleteByIdIn(List<ContractProductEntity> list, String corpid) throws XbbException {
        List<Long> deleteIdIn = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        list.forEach(item->{
            deleteIdIn.add(item.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getType() + "_" + corpid + "_" + item.getId());
            insertDTO.setParent(corpid + "_" + item.getContractId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getType());
            Map<String,Object> sourceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            sourceMap.put(StringConstant.DEL,DelEnum.DELETE.getDel());
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);

        });
        Integer success = contractProductDao.deleteByIdIn(deleteIdIn, corpid);
        paasEsModel.updateBatch(insertDTOList);
        return success;
    }

    @Override
    public Integer deleteBatch(List<ContractProductEntity> list, String corpid, Integer del) throws XbbException {
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        List<Long> deleteIdIn = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        list.forEach(item->{
            if (Objects.isNull(item.getContractId())) {
                return;
            }
            deleteIdIn.add(item.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getType() + "_" + corpid + "_" + item.getId());
            insertDTO.setParent(corpid + "_" + item.getContractId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getType());
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getIndex());
            Map<String,Object> sourceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            sourceMap.put(StringConstant.DEL,del);
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);

        });
        if (CollectionsUtil.isEmpty(deleteIdIn)) {
            return 0;
        }
        Integer success = contractProductDao.deleteBatch(deleteIdIn, corpid, del);
        paasEsModel.updateBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE);
        return success;
    }

    @Override
    public List<ContractProductEntity> getById(List<Long> contractProductIdList, String corpid) throws XbbException {
        if (CollectionsUtil.isEmpty(contractProductIdList)) {
            return new ArrayList<>();
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put("idIn", contractProductIdList);
        return contractProductDao.findEntitys(param);
    }

    @Override
    public Integer updateShipNum(List<ContractProductEntity> updateList, String corpid) throws XbbException {
        long now = DateTimeUtil.getInt();
        updateList.forEach(item->{
            item.setUpdateTime(now);
        });
        Integer result = contractProductDao.updateShipNum(updateList,corpid);
        List<InsertDTO> updateDTOList = new ArrayList<>();
        for (ContractProductEntity entity : updateList){
            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            JSONObject object = new JSONObject();
            object.put(ContractProductSubFormEnum.SHIPMENTS_NUM.getDataAttr(), entity.getShipmentsNum());
            map.put(StringConstant.JSON_DATA, object);
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getType() + "_" + entity.getCorpid() + "_" + entity.getId());
            insertDTO.setParent(entity.getCorpid() + "_" + entity.getContractId());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
            updateDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(updateDTOList);
        return result;
    }

    @Override
    public  List<ContractProductEntity> findWaitOutProductEntitys(Map<String, Object> param) throws XbbException {
        return contractProductDao.findWaitOutProductEntitys(param);
    }

    @Override
    public  List<ContractProductEntity> findWaitPurchaseProductEntitys(Map<String, Object> param) throws XbbException {
        return contractProductDao.findWaitPurchaseProductEntitys(param);
    }

    @Override
    public  Integer findWaitPurchaseProductCount(Map<String, Object> param) throws XbbException {
        return contractProductDao.findWaitPurchaseProductCount(param);
    }

    @Override
    public List<ContractProductEntity> getWaitOutstockProductByProductIdIn(Map<String, Object> param) {
        return contractProductDao.getWaitOutstockProductByProductIdIn(param);
    }

    @Override
    public List<ContractProductEntity> getInstockProductAndContractProdcut(Map<Long , Long> stockFlowAndContractProduct , String corpid){
        return contractProductDao.getInstockProductAndContractProdcut(stockFlowAndContractProduct , corpid);
    }

    @Override
    public void updateInstockProductById(List<ContractProductEntity> contractProductEntityList, String corpid){
        long now = DateTimeUtil.getInt();
        contractProductEntityList.forEach(item->{
            item.setUpdateTime(now);
        });
        contractProductDao.updateInstockProductById(contractProductEntityList, corpid);
    }

    @Override
    public void updateWaitOutStatusById(List<Long> contractIdIn, String corpid, Integer status, Integer type) throws XbbException {
        contractProductDao.updateWaitOutStatusById(contractIdIn, corpid, status, type);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.ID_IN, contractIdIn);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<InsertDTO> updateDTOList = new ArrayList<>();
        List<ContractProductEntity> entitys = this.findEntitys(param);
        for (ContractProductEntity entity : entitys){
            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            JSONObject object = new JSONObject();
            object.put(ContractProductSubFormEnum.STATUS.getDataAttr(), entity.getStatus());
            map.put(StringConstant.JSON_DATA, object);
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getType() + "_" + entity.getCorpid() + "_" + entity.getId());
            insertDTO.setParent(entity.getCorpid() + "_" + entity.getContractId());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
            updateDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(updateDTOList);
    }

    @Override
    public Integer findWaitOutStockProductCount(Map<String, Object> param) {
        return contractProductDao.findWaitOutStockProductCount(param);
    }

    @Override
    public Integer updateProductInfoByParentId(String corpid, Long productId, String productName, String productNo, String specification) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("parentId", productId);
        param.put("del", 0);
        param.put("columns", " id, contract_id ");
        List<ContractProductEntity> contractProductEntityList = findEntitys(param);
        long now = DateTimeUtil.getInt();
        Integer result = contractProductDao.updateProductInfoByParentId( corpid,  productId,  productName,  productNo,  specification, now);
        Integer pageSize = 5000;
        List<ContractProductEntity> resultList;
        Integer allTotal = contractProductEntityList.size();
        Integer index = allTotal/pageSize + 1;
        Integer page = 0;
        Integer toIndex = 5000;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(ContractProductSubFormEnum.PRODUCT_NO.getDataAttr(), productNo);
        jsonObject.put(ContractProductSubFormEnum.PRODUCT_NAME.getDataAttr(), productName);
        jsonObject.put(ContractProductSubFormEnum.SPECIFICATION.getDataAttr(), specification);
        for (int j = 0; j < index; j++) {
            if (toIndex > allTotal) {
                toIndex = allTotal;
            }
            resultList = contractProductEntityList.subList(page, toIndex);
            if (CollectionsUtil.isNotEmpty(resultList)) {
                updateEsContractProduct(corpid, resultList, jsonObject, now);
                page = page + pageSize;
                toIndex = page + pageSize;
            }
        }
        return result;
    }

    private void updateEsContractProduct(String corpid, List<ContractProductEntity> entitys, JSONObject object, Long updateTime ) throws XbbException {
        if (CollectionsUtil.isEmpty(entitys)) {
            return;
        }
        List<InsertDTO> updateList = new ArrayList<>();
        for (ContractProductEntity entity : entitys){
            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put(StringConstant.JSON_DATA, object);
            map.put(StringConstant.UPDATE_TIME, updateTime);
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
            insertDTO.setParent(corpid + "_" + entity.getContractId());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
            updateList.add(insertDTO);
        }
        paasEsModel.updateBatch(updateList);
    }
}
